( function ($){

/*  TODO: write some plugin code ... */

	/* This makes our musicPlayer function accessable 
	 * like any other jquery function:
	 * e.g. $("#mydivid").musicPlayer(playlist) */
	$.fn.musicPlayer = function(playlist, options){
		/* loop through all musicPlayer elements givin 
		 * this refers to the elements (the whole collection of elements)  */ 
		return this.each( function(){
			
			/************************************
			 ****** SETUP CODE AND GLOBALS ******
			 ************************************/
			var defaultOptions = {
				autoplay: true,
				errorMsg: "Undskyld kan spille sangen!",
				playerTitle: "The latest and greatest music player"
				};
				
			var realOptions = $.extend(defaultOptions, options); 			
			
			/************************************/
			
			
			/************************************
			 ****** GENERATING HTML CODE  *******
			 ************************************/
			/* for browsers that support the html5 audio element */
			//if (Modernizr.audio == true){
				/* Generating the audio div */
				var audioElem = document.createElement("audio");
				$(audioElem).attr("id", "audioPlayer");
				$(audioElem).append('<source src"http://93.95.224.133/fgstests/oggs/flikkflakk.ogg" type="audio/ogg" />');
				$(audioElem).append('<p>Sorry but your browser does not support this player</p>');
				//$(this).add(audioElem);
				$(audioElem).appendTo(this);
				
			//}
			//else{
				// use flash player check out NiftyPlayer - http://www.varal.org/niftyplayer/
			//}
			

			/* Adding the volume dive */
			var divVolume = document.createElement("div");
			$(divVolume).attr("id", "volume");
			$(divVolume).append('<input type="range" value="30" min="0" max="100" step="2" title="Adjust volume"/>');
			//$(this).add(divVolume); /* then adding the volume div to the main plugin div */
			$(divVolume).appendTo(this);
			$(divVolume).hide();
			
				
			/* Adding div for the player title */
			var titleDiv = document.createElement("div");
			$(titleDiv).attr("id", "player-title").attr("class", "player-frame");
			var playerTitleStr = '<span class="title">' + realOptions.playerTitle +'</span>';
			$(titleDiv).append(playerTitleStr);
			//$(this).add(titleDiv);
			$(titleDiv).appendTo(this);
			
			
			/* Adding div for the player controls */
			var controlDiv = document.createElement("div");
			$(controlDiv).attr("id", "player-control").attr("class","player-frame");
			var controlUL = document.createElement("ul");
			$(controlUL).attr("id","control-buttons");
			
			
			/* prev button to the ul element */
			prevLI = '<li class="ui-state-default ui-corner-all" title="Previous song">';
			prevLI += '<span class="ui-icon ui-icon-seek-prev"></span>';
			prevLI += '</li>';
			$(controlUL).append(prevLI); /* adding the prev button to the ul tag */
			
			playLI = '<li class="ui-state-default ui-corner-all" title="Play/Pause">';
			playLI += '<span class="ui-icon ui-icon-play"></span>';
			playLI += '</li>';
			$(controlUL).append(playLI);
			
			nextLI = '<li class="ui-state-default ui-corner-all" title="Next song">';
			nextLI += '<span class="ui-icon ui-icon-seek-next"></span>';
			nextLI += '</li>';
			$(controlUL).append(nextLI);

			soundLI = '<li class="ui-state-default ui-corner-all" title="Sound on/off">';
			soundLI += '<span class="ui-icon ui-icon-volume-on"></span>';
			soundLI += '</li>';
			$(controlUL).append(soundLI);
			
			$(controlDiv).append(controlUL); /* adding the controls buttons to the div */
			
			//if (Modernizr.range == true){
				var inputRange = document.createElement("input");
				$(inputRange).attr("id", "progress").attr("type","range").attr("min", "0").attr("max","100").attr("step","1");
				$(controlDiv).append(inputRange);
			//}
			//else{
			//	/* fall back to a javascript slider */
			//	/* var inputRange = ??? */
			//	$(controlDiv).add(inputRange);
			//	alert("No support for range!");
			//}
			
			$(controlDiv).append('<span></span>'); /* for storing the progress in time presentation  e.g. 2:33 */
			//$(this).append(controlDiv); /* then add the whole control div to the root plugin div */
			$(controlDiv).appendTo(this);
			
			
			/* Adding the playlist div */
			var playlistDiv = document.createElement("div");
			$(playlistDiv).attr("id","player-playlist").attr("class", "player-frame");
			$(playlistDiv).append('<span class="title">Playlist:</span>');
			var playlistUL = document.createElement("ul");
			$(playlistUL).attr("id", "playlist");
			for (var i = 0; i < playlist.length; i++){
				var playlistLI = document.createElement("li");
				var playlistA = document.createElement("a");
				$(playlistA).attr("href", playlist[i]).attr("id", "song"+(i+1)).attr("onclick", "return false");
				$(playlistA).append( getFileNameFromUrl(playlist[i]) ); /* adding only the filename as the visable text in the a element */
				$(playlistLI).append(playlistA); /* add "<li><a ...>...</a></li>" for each song to the playlist ul */
				$(playlistUL).append(playlistLI);
			}
			$(playlistDiv).append(playlistUL); /* then add the playlist ul to the playlist div */
			//$(this).add(playlistDiv); /* and the whole playlist div to the root plugin div */
			$(playlistDiv).appendTo(this);
			
			/* Adding the status div */
			var statusDiv = document.createElement("div");
			$(statusDiv).attr("id","player-status").attr("class", "player-frame");
			$(statusDiv).append('<marquee loop="infinite">play a song!</marquee>');
			$(this).append(statusDiv);
			$(statusDiv).appendTo(this);
			/************************************/

			/*then some default values */
				/* setting some default settings */
			audio = $(audioElem).get(0); /* getting the audio */
			audio.volume = realOptions.volume;
			
			if (realOptions.autoplay){
				playSong( $("#song1") );
			}
			
			/************************************
			 ****** EVENT HANDLERS   ************
			 ************************************/
			/* when a user selects from playlist */	
			$("#playlist li a").live("click", function(){
				 playSong(this);
			});
			
			/* hover over buttons - changing the css in buttons */
			$("#control-buttons li").mouseenter(function() {
				$(this).addClass('ui-state-hover');
			});
			
			/* event for mouseleave - changing the css back to regular */
			$("#control-buttons li").mouseleave(function() {
				$(this).removeClass("ui-state-hover");
			});
			
			/* event for  play-button  */
			$("#control-buttons li .ui-icon-play").live( "click", function() {
				$(this).removeClass("ui-icon-play"); /* remove play icon */
				$(this).addClass("ui-icon-pause"); /* setting the pause icon instead */
				audio.play();
			});	
			
			/* event for pause-button */
			$("#control-buttons li .ui-icon-pause").live( "click", function() {
				$(this).removeClass("ui-icon-pause"); /*removing pause icon */
				$(this).addClass("ui-icon-play"); /* setting the play icon instead */
				audio.pause();
			});				
			
			/* event for mute-button */
			$("#control-buttons li .ui-icon-volume-on").live( "click", function() {
				$(this).removeClass("ui-icon-volume-on");
				$(this).addClass("ui-icon-volume-off");
				audio.volume = 0.0;
			});	
			
			/* event for next-button */
			$("#control-buttons li .ui-icon-seek-next").live( "click", function() {
				var n = $("#player-playlist li a.playing-song");
				
				/* checking if song is the last on list */
				if ($(n).attr("id") != ("song" + playlist.length) )
					n = $(n).parent().next("li").children();
				else
					n = $("#song1"); /* then get the first song */				
					
				playSong(n);
			});				
			
			/* event for prev-button */
			$("#control-buttons li .ui-icon-seek-prev").live( "click", function() {
				var n = $("#player-playlist li a.playing-song");
				
				/* checking if song is the first on list */
				if ($(n).attr("id") != ("song1") )
					n = $(n).parent().prev("li").children();
				else
					n = $( ("#song" + playlist.length) ); /* then get the last song */				
				
				playSong(n);	
			});	
			
			/* event handler for mute on/off and */
			$("#control-buttons li .ui-icon-volume-off").live("click", function() {
				$(this).removeClass("ui-icon-volume-off");
				$(this).addClass("ui-icon-volume-on");
				audio.volume = Number($("#volume").val())/100;
			});	

			/* event handler for showing the volume div */
			$("#control-buttons li .ui-icon-volume-on").mouseenter(function() {
				$("#volume").show();
			});			
			
			/* event handler to hide the volume div */
			$("#volume").mouseleave(function(){
				$("#volume").hide();
			});
			
			/* event handler when volume is changed */
			$("#volume input").change(function() {
				audio.volume = Number(this.value)/100;
			});		
			
			/* event for song ended then play next song */
			$("#audioPlayer").bind("ended", function(){
				var n = $("#player-playlist li a.playing-song");
				
				/* checking if song is the last on list */
				if ($(n).attr("id") != ("song" + playlist.length) )
					n = $(n).parent().next("li").children();
				else
					n = $("#song1"); /* then get the first song */	
				
				playSong(n);
			});
			
			/* Event handler for the progress in a playing song */
			$(audio).bind('timeupdate', function() {
				var rem = parseInt(audio.duration - audio.currentTime, 10),
				pos = (audio.currentTime / audio.duration) * 100,
				mins = Math.floor(rem/60,10),
				secs = rem - mins*60;
				
				$("#progress").next().text(mins + ':' + (secs > 9 ? secs : '0' + secs));
				$("#progress").val(pos);
			});
				
			$(audio).bind('progress', function() {
					if ((audio.buffered != undefined) && (audio.buffered.length != 0)) {
						var loaded = parseInt(((audio.buffered.end(0) / audio.duration) * 100), 10);
						$("#progress").val(loaded);
					}
			});
			
			
			$("#progress").change(function() {
				audio.currentTime = (Number(this.value)/100) * audio.buffered.end(0) ;
			});
			
			/************************************/

			
			/************************************
			 ****** HELPER FUNCTIONS ************
			 ************************************/
			 
			/* helper function for rendering the playlist  
			 * input an url returns the filename */ 
			function getFileNameFromUrl(url){
				var i = url.lastIndexOf("/"); 
				return url.substr(i+1);
			}			
			
			/* helper function for play from playlist, next and prev buttons */
			function playSong(el){
				var text = $(el).attr("href"); /* getting the url of song */
				var songName = $(el).text();
				$("#player-status marquee").text("now playing: " + songName ); /* changing the display status */
				$(".playing-song").removeClass("playing-song");  /* removing css class from last playing song */
				$(el).addClass("playing-song"); /* setting a css class so that this li is the current song */
				$("#control-buttons li .ui-icon-play").removeClass("ui-icon-play").addClass("ui-icon-pause"); /* remove play icon and set pause icon */
				audio.src = text;
				audio.play();
			}			
			/************************************/
		});
	}
})(jQuery);